/**
 * 解决微信浏览器下部分IOS设备自动播放问题
 * @param {String} id 音频标签id字符串
 */
var audioAutoPlay = function (id) {
    var audio = document.getElementById(id),
            play = function () {
                audio.play();
                document.removeEventListener('touchstart', play, false);
            };
    audio.play();
    document.addEventListener('WeixinJSBridgeReady', function () {
        play();
    }, false);
    document.addEventListener('touchstart', play, false);
}
audioAutoPlay('openmusic');

/**
 * 基于 DeviceMotionEvent 实现的html版摇一摇
 */
if(window.DeviceMotionEvent) {
    var SHAKE_THRESHOLD = 1000;
    var SAMPLING_FREQUENCY = 250;
    var last_update = 0;
    var x = y = z = last_x = last_y = last_z = 0;
    var isHandling = false;

    window.addEventListener('devicemotion', handleDeviceMotion, false);

    function handleDeviceMotion(e) {
        e = e || window.event;
        var acceleration = e.accelerationIncludingGravity; //获取加速度分量
        var curTime = +new Date();

        //采样处理间隔
        if((curTime - last_update) > SAMPLING_FREQUENCY) {
            var diffTime = curTime - last_update;
            last_update = curTime; 
            x = acceleration.x;
            y = acceleration.y;
            z = acceleration.z;
            var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
            if(speed > SHAKE_THRESHOLD) {
                buildDiv(speed);
                showSomething();
                last_x = x;
                last_y = y;
                last_z = z;
            }
        }

    }

    function showSomething() {
        if(!isHandling) {
            isHandling = true;
            document.getElementById('mark').innerText = '不能摇';
            alert('感谢参与');
        }
    }

    setInterval(function () {
        isHandling = false;
        document.getElementById('mark').innerText = '可以摇';
    }, 5000);

    function buildDiv(text) {
        // var div = document.getElementById('showText');
        var div = document.createElement('div');
        div.innerText = text;
        document.body.appendChild(div);
    }
} else {
    alert('你浏览区暂不支持摇一摇');
}